package com.hzlx.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;


//自定义认证提供者
@Component
@Slf4j
public class AccessReactiveAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication,
                                             AuthorizationContext context) {
        // 1. 获取请求路径
        String path = context.getExchange().getRequest().getPath().toString();
        String method = context.getExchange().getRequest().getMethod().toString().toLowerCase(); //     GET/POST
        String perm = String.format("%s%s",method, path.replaceAll("/",":")).toLowerCase();
        // 2. 结合用户权限判断
        return authentication
                .map(auth -> new AuthorizationDecision(checkAccess(auth, perm)))
                .defaultIfEmpty(new AuthorizationDecision(false));
    }
    private boolean checkAccess(Authentication auth, String perm) {
        // 示例：路径需包含用户角色
        return auth.getAuthorities().stream()
                .anyMatch(role -> {
                    log.info("鉴权：{}-{}",role.getAuthority(),perm);
                    return perm.contains(role.getAuthority());
                });
    }
}
